from fastapi import APIRouter, HTTPException, Query, Depends
from typing import List, Optional
from app.services.discourse import DiscourseService
from app.config import settings

router = APIRouter(prefix="/discourse", tags=["discourse"])

def get_discourse_service() -> DiscourseService:
    """获取 Discourse 服务实例"""
    if not all([settings.DISCOURSE_BASE_URL, settings.DISCOURSE_API_KEY, settings.DISCOURSE_USERNAME]):
        raise HTTPException(
            status_code=500, 
            detail="Discourse configuration is incomplete. Please check DISCOURSE_BASE_URL, DISCOURSE_API_KEY, and DISCOURSE_USERNAME in your environment variables."
        )
    
    return DiscourseService(
        base_url=settings.DISCOURSE_BASE_URL,
        api_key=settings.DISCOURSE_API_KEY,
        username=settings.DISCOURSE_USERNAME
    )

@router.get("/posts/latest")
async def get_latest_posts(
    limit: int = Query(10, ge=1, le=100),
    discourse_service: DiscourseService = Depends(get_discourse_service)
):
    """获取最新的帖子"""
    try:
        posts = await discourse_service.get_latest_posts(limit=limit)
        return {
            "posts": posts,
            "count": len(posts),
            "limit": limit
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/posts/search")
async def search_posts(
    q: str = Query(..., description="搜索关键词"),
    limit: int = Query(20, ge=1, le=100),
    discourse_service: DiscourseService = Depends(get_discourse_service)
):
    """搜索帖子"""
    try:
        posts = await discourse_service.search_posts(query=q, limit=limit)
        return {
            "query": q,
            "posts": posts,
            "count": len(posts),
            "limit": limit
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/posts/by-tags")
async def search_posts_by_tags(
    tags: List[str] = Query(..., description="标签列表"),
    limit: int = Query(20, ge=1, le=100),
    discourse_service: DiscourseService = Depends(get_discourse_service)
):
    """通过标签搜索帖子"""
    try:
        posts = await discourse_service.search_posts_by_tags(tags=tags, limit=limit)
        return {
            "tags": tags,
            "posts": posts,
            "count": len(posts),
            "limit": limit
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/posts/with-any-tags")
async def get_posts_with_any_tags(
    tags: List[str] = Query(..., description="标签列表（OR 查询）"),
    limit: int = Query(20, ge=1, le=100),
    discourse_service: DiscourseService = Depends(get_discourse_service)
):
    """获取包含任意指定标签的帖子（OR 查询）"""
    try:
        posts = await discourse_service.get_posts_with_any_tags(tags=tags, limit=limit)
        return {
            "tags": tags,
            "query_type": "OR",
            "posts": posts,
            "count": len(posts),
            "limit": limit
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/posts/with-all-tags")
async def get_posts_with_all_tags(
    tags: List[str] = Query(..., description="标签列表（AND 查询）"),
    limit: int = Query(20, ge=1, le=100),
    discourse_service: DiscourseService = Depends(get_discourse_service)
):
    """获取包含所有指定标签的帖子（AND 查询）"""
    try:
        posts = await discourse_service.get_posts_with_all_tags(tags=tags, limit=limit)
        return {
            "tags": tags,
            "query_type": "AND",
            "posts": posts,
            "count": len(posts),
            "limit": limit
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/categories/{category_id}/topics")
async def get_category_topics(
    category_id: int,
    limit: int = Query(20, ge=1, le=100),
    discourse_service: DiscourseService = Depends(get_discourse_service)
):
    """获取特定分类下的主题"""
    try:
        topics = await discourse_service.get_category_topics(category_id=category_id, limit=limit)
        return {
            "category_id": category_id,
            "topics": topics,
            "count": len(topics),
            "limit": limit
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/topics/{topic_id}/posts")
async def get_topic_posts(
    topic_id: int,
    discourse_service: DiscourseService = Depends(get_discourse_service)
):
    """获取特定主题下的所有帖子"""
    try:
        posts = await discourse_service.get_topic_posts(topic_id=topic_id)
        return {
            "topic_id": topic_id,
            "posts": posts,
            "count": len(posts)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/posts")
async def create_post(
    title: str,
    content: str,
    category_id: Optional[int] = None,
    discourse_service: DiscourseService = Depends(get_discourse_service)
):
    """创建新帖子"""
    try:
        result = await discourse_service.create_post(
            title=title,
            content=content,
            category_id=category_id
        )
        
        if "error" in result:
            raise HTTPException(status_code=400, detail=result["error"])
        
        return {
            "message": "Post created successfully",
            "result": result
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
